<template>
  <div id="productList" class="product-list" >
    <div v-for="product in products" :key="product.id" class="product-item" @click="router.push({path:`/product/details/${product.id}`})">
      <div
          class="product-thumbnail"
          :style="{ backgroundImage: `url('${product.cover}')` }"
      ></div>
      <div class="product-title">{{ product.title }}</div>
      <div class="product-price">{{ product.price / 100 }}</div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import apis from "@/config/api-config.js";
import getResponse from "@assets/js/http-client.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";


// 响应式商品数据
const products = ref([]);
// 商品分页查询参数
const params = {
  pageNum: 1,
  pageSize: 12,
  keyword: '',
}
//true:正在加载数据;false:已完成加载
const loading = ref(false);
/**
 * 分页查询第一页数据
 * @param restart true:重新从第一页开始查询数据;false:查询下一个数据
 * @param keyword 搜索关键字
 * @returns {Promise<void>}
 */
const fetchProducts = async (restart, keyword) => {
  if (loading.value) {
    return;
  }
  loading.value = true;
  if (restart) {
    //查询第一页数据
    params.pageNum = 1;
    products.value = [];
    params.keyword = keyword;
  } else {
    //查询下一个数据
    params.pageNum++;
  }
  let url = apis.product.productList.url;
  let type = apis.product.productList.type;
  let result = await getResponse(url, type, params);
  loading.value = false;
  if (200 !== result.code) {
    ElMessage.error(result.message);
    return;
  }
  let productList = result.data.records;
  if (productList === null || 0 === productList.length) {
    console.info('未查询到任何商品数据');
    productList = [];
  }
  products.value.push(...productList);
  let current = result.data.current;//当前页
  let pages = result.data.pages;//总页数
  if (current >= pages) {
     ElMessage.warning("没有更多商品数据");
     params.pageNum=pages+1;
  }
};
defineExpose({fetchProducts})

onMounted(() => {
  fetchProducts(true, '');
});
</script>

<style scoped>
.product-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 40px;
}

.product-item {
  flex: 0 0 calc(25% - 20px);
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.product-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.product-item {
  transition: all 0.3s ease;
}

.product-thumbnail {
  width: 100%;
  height: 200px;
  background-color: #eee;
  background-size: cover;
  background-position: center;
}

.product-title {
  padding: 10px;
  font-size: 14px;
  text-align: center;
}

.product-price {
  padding: 0 10px 10px;
  font-size: 16px;
  color: #e60012;
  text-align: center;
}
</style>